﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Common;
using System.Net;
using System.IO;
using System.Text;
using DAL;
using Model;
namespace UI
{
    public partial class activessstest : System.Web.UI.Page
    {
        WeiXin wx = new WeiXin();
        public string signature = "";
        public string noncestr = "";
        public long timestamp = 0;
        public ActiveInfo active = new ActiveInfo();
        public EwmInfo ewm = new EwmInfo();
        public UserInfo uinfo = new UserInfo();
        public float prizemoney = 0;
        public bool hastake = false;
        public int istake = 0;
        public int userid = 0;
        public int shareuserid = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            //WeiXin wx = new WeiXin();
            //position = wx.HttpGet("http://apis.map.qq.com/ws/coord/v1/translate?locations=34.11,116.22&type=1&key=2STBZ-Q6VA4-FSAU4-DO7ZG-YN7T5-ZZFSF", "");
            //SaveFile();
            int id = DataConvert.ToInt(DESEncrypt.Decrypt(JobRequest.GetRequestString("id")));
            string rid = JobRequest.GetRequestString("rid");
            if (id == 1329 || id == 1327)
            {
                Response.Redirect("http://www.mengshen666.cn/activess.aspx?id=" + JobRequest.GetRequestString("id"));
            }
            if (Request["code"] == null && B.MyUser == null)
            {
                Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1a4dea3fd54864b9&redirect_uri=" + Server.UrlEncode("http://www.mengshen666.cn/activesss.aspx?id=" + JobRequest.GetRequestString("id") + "&rid=" + rid) + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
            }
            else
            {
                ConfigInfo info = ConfigDAL.GetConfig();
                string token = info.Token;
                string ticket = info.Ticket;
                noncestr = Util.CreateNonce_str();
                timestamp = Util.CreateTimestamp();
                signature = GetSignature(ticket, noncestr, timestamp, Request.Url.ToString());
                userid = DataConvert.ToInt(DESEncrypt.Decrypt(JobRequest.GetRequestString("userid")));
                shareuserid = userid;
                
                if (B.MyUser == null)
                {
                    string result = wx.HttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1a4dea3fd54864b9&secret=75fac3337cd918fd762b48f368cba18e&code=" + Request["code"] + "&grant_type=authorization_code", "");
                    string str = wx.HttpGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + wx.ConvertJson(result).access_token + "&openid=" + wx.ConvertJson(result).openid + "&lang=zh_CN", "");
                    dynamic user = wx.ConvertJson(str);

                    //UserInfo bak = UserDAL.FindByHeadImg(user.province, user.city, user.nickname, user.sex);
                    //if (bak.ID > 0)
                    //{
                    //    UserDAL.UpdateOpenID(user.openid, user.province, user.city, user.nickname, user.sex);
                    //}


                    uinfo = UserDAL.FindByOpenID(user.openid);
                    if (uinfo.ID == 0)
                    {
                        uinfo.OpenID = user.openid;
                        uinfo.NickName = user.nickname;
                        uinfo.HeadImg = user.headimgurl;
                        uinfo.Mobile = "";
                        uinfo.UserPwd = "";
                        uinfo.Province = user.province;
                        uinfo.City = user.city;
                        uinfo.Area = "";
                        uinfo.Sex = user.sex;
                        uinfo.Money = 0;
                        uinfo.Role = 1;
                        uinfo.State = -1;
                        uinfo.EndDate = DateTime.Now;
                        uinfo.CreateDate = DateTime.Now;
                        int ID = UserDAL.Save(uinfo);
                        uinfo.ID = ID;
                        B.MyUser = uinfo;
                    }
                    else
                    {
                        B.MyUser = uinfo;
                    }
                }
                else
                {
                    if (B.MyUser.ID > 0)
                    {
                        uinfo = UserDAL.FindOneByID(B.MyUser.ID);
                    }
                    else
                    {
                        B.MyUser = null;
                        Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1a4dea3fd54864b9&redirect_uri=" + Server.UrlEncode("http://www.mengshen666.cn/activesss.aspx?id=" + JobRequest.GetRequestInt("id") + "&rid=" + rid) + "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
                    }
                }
                ewm = EwmDAL.FindOneByID(DataConvert.ToInt(DESEncrypt.Decrypt(JobRequest.GetRequestString("id"))));
                active = ActiveDAL.FindOneByID(ewm.ActiveID);
                active.Context = Commons.TranRN(active.Context);
                if (active.State == 4) { active.State = 2; }
                prizemoney = ewm.Money;
                if (prizemoney > 0) { hastake = true; }
                prizemoney = DataConvert.ToFloat(prizemoney.ToString("0.00"));
                VisitRecordInfo visit = new VisitRecordInfo()
                {
                    UserID = uinfo.ID,
                    SID = active.ID,
                    Province = "",
                    City = "",
                    Area = "",
                    Lat = 0,
                    Lng = 0,
                    Address = "",
                    CreateID = active.UserID,
                    FCount = 1,
                    Flag = 1,
                    CreateDate = DateTime.Now
                };
                VisitRecordDAL.Save(visit);
                ActiveDAL.IncClickCount(active.ID);













                //ceshi
                //string result2 = wx.HttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1a4dea3fd54864b9&secret=75fac3337cd918fd762b48f368cba18e&code=" + Request["code"] + "&grant_type=authorization_code", "");
                //string str2 = wx.HttpGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + wx.ConvertJson(result2).access_token + "&openid=" + wx.ConvertJson(result2).openid + "&lang=zh_CN", "");
                //Commons.Log(str2);
                /*
                for (int i = 0; i < 9985; i++)
                {
                    UserInfo uu = new UserInfo();
                    uu.OpenID = "";
                    uu.NickName = "";
                    uu.HeadImg = "";
                    uu.Mobile = "";
                    uu.UserPwd = "";
                    uu.Province = "";
                    uu.City = "";
                    uu.Area = "";
                    uu.Sex = 1;
                    uu.Money = 0;
                    uu.Role = 1;
                    uu.CreateDate = DateTime.Now;
                    UserDAL.Save(uu);
                }
                */
            }


        }
        public static string GetSignature(string jsapi_ticket, string noncestr, long timestamp, string url)
        {
            var string1Builder = new StringBuilder();
            string1Builder.Append("jsapi_ticket=").Append(jsapi_ticket).Append("&")
                          .Append("noncestr=").Append(noncestr).Append("&")
                          .Append("timestamp=").Append(timestamp).Append("&")
                          .Append("url=").Append(url.IndexOf("#") >= 0 ? url.Substring(0, url.IndexOf("#")) : url);
            string string1 = string1Builder.ToString();
            return Util.Sha1(string1);
        }
        public void SaveFile(string downurl, string saveurl)
        {
            int blocksize = 1024 * 100;
            byte[] buffer = new byte[blocksize];

            string strFileName = HttpContext.Current.Server.MapPath(saveurl);

            WebRequest request = WebRequest.Create(downurl);
            WebResponse response = request.GetResponse();
            Stream reader = response.GetResponseStream();

            FileStream writer = new FileStream(strFileName, FileMode.OpenOrCreate, FileAccess.Write);
            int c = 0;
            while ((c = reader.Read(buffer, 0, buffer.Length)) > 0)
            {
                writer.Write(buffer, 0, c);
            }
            writer.Close();
            writer.Dispose();
            reader.Close();
            reader.Dispose();
            response.Close();
        }

        /*
        public void DownLoad()
        {
            string stUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=zPPAe-eDDh4thYlGU8NdACaO8rg_2UZZCGi6oZg56Hkh-Wdgp_QbrxwyvJY9-WWTt4Hqp84MjkwWgSSEfpvaghabo6oMd0iYhxbiKqo7aTWhFOrqEPPqVcjTDi4P1RUsWSUhAEAQMO&media_id=7GJqPSuP9cNK_QyKgBvmydEDj1kocfpCODBXOWChoHwL_sLrt3dxKREv8asOy0_G";

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(stUrl);

            req.Method = "GET";
            using (WebResponse wr = req.GetResponse())
            {
                HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();

                strpath = myResponse.ResponseUri.ToString();
                WebClient mywebclient = new WebClient();
                savepath = Server.MapPath("upload") + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + (new Random()).Next().ToString().Substring(0, 4) + ".jpg";
                try
                {
                    mywebclient.DownloadFile(strpath, savepath);
                    file = savepath;
                }
                catch (Exception ex)
                {
                    savepath = ex.ToString();
                }

            }
        }
        */
    }
}